﻿using System.ComponentModel.DataAnnotations;

namespace TK.Common.DataAnnotations
{
    /// <summary>
    /// Specifies the maximum value allowed in a property.
    /// </summary>
    public class MaxValueAttribute : ValidationAttribute
    {
        /// <summary>
        /// ctor
        /// </summary>
        public MaxValueAttribute(int maxValue, bool includeMaxValue = true)
        {
            MaxValue = maxValue;
            IncludeMaxValue = includeMaxValue;
        }

        /// <summary>
        /// 最大值
        /// </summary>
        public decimal MaxValue { get; set; }

        /// <summary>
        /// 是否包含最大值
        /// </summary>
        public bool IncludeMaxValue { get; set; }

        /// <summary>
        /// Determines whether the specified value of the object is valid.
        /// </summary>
        public override bool IsValid(object value)
        {
            if (value != null)
            {
                if (decimal.TryParse(value.ToString(), out var curVal))
                {
                    return IncludeMaxValue ? curVal <= MaxValue : curVal < MaxValue;
                }
            }

            return true;
        }
    }
}
